package com.example.contentprovider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class MyContentProvider extends ContentProvider {
    private static final String AUTHORITY = "com.gdcp.demo";
    private MySQLiteOpenHelper openHelper;
    private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        uriMatcher.addURI(AUTHORITY, "fruit", 1);
    }


    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int rows = 0;
        SQLiteDatabase writableDatabase = openHelper.getWritableDatabase();
        if (uriMatcher.match(uri) == 1) {
            rows = writableDatabase.delete("fruit", selection, selectionArgs);
        }
        writableDatabase.close();
        return rows;
    }

    @Override
    public String getType(Uri uri) {
        // TODO: Implement this to handle requests for the MIME type of the data
        // at the given URI.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase writableDatabase = openHelper.getWritableDatabase();
        // 插入数据  首先根据uri判断要插入哪一张表
        if (uriMatcher.match(uri) == 1) {
            // 如果匹配结果是1 说明路径中包括student 要插入的是学生表
            writableDatabase.insert("fruit", null, values);
        }
        writableDatabase.close();
        return null;
    }

    @Override
    public boolean onCreate() {
        openHelper = new MySQLiteOpenHelper(getContext(),"fru.db", null, 1);
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteDatabase readableDatabase = openHelper.getReadableDatabase();
        if (uriMatcher.match(uri) == 1) {
            return readableDatabase.query("fruit", projection, selection, selectionArgs, null, null, sortOrder);
        }
        return null;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        int rows = 0;
        SQLiteDatabase writableDatabase = openHelper.getWritableDatabase();
        if (uriMatcher.match(uri) == 1) {
            rows = writableDatabase.update("fruit", values, selection, selectionArgs);
        }
        writableDatabase.close();
        return rows;
    }
}